<template>
  <div class="user-profile-container">

    <cneter>
        <h2>基本资料</h2>
    </cneter>

    <hr style="border: 1px dashed #ccc; margin: 20px 0;" />
    
    <div class="profile-inner">
      <!-- 头像及左侧信息 -->
      <div class="avatar-section">
        <div class="avatar-wrapper">
          <el-upload
            ref="uploadRef"
            class="avatar-uploader"
            :show-file-list="false"
            :headers="{'Authorization': TokenStore.token}"
            action="/api/file/upload"
            name="file"
            :on-success="FileUpload"
            :on-error="handleUploadError"
          >
            <img v-if="imgUrl" :src="imgUrl" class="avatar-image" alt="用户头像" />
            <div v-else class="avatar-placeholder">
              <i class="el-icon-user"></i>
            </div>
          </el-upload>
          <el-button 
            type="primary" 
            size="small" 
            class="change-avatar-btn"
            @click="uploadRef.$el.querySelector('input').click()"
          >
            更换头像
          </el-button>
        
        </div>
        <div class="username">用户名：{{ InfoStore.info.username || '未设置用户名' }}</div>
      </div>

      <!-- 表单区域 -->
      <el-form 
        :model="userInfo" 
        :rules="rules" 
        label-width="100px" 
        size="medium"
        class="form-section"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户ID">
              <el-input v-model="userInfo.id" disabled></el-input>
            </el-form-item>
            <el-form-item label="用户昵称" prop="nickname">
              <el-input v-model="userInfo.nickname" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userInfo.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="个人简介">
              <el-input 
                v-model="userInfo.user_profile" 
                type="textarea" 
                :rows="4" 
                placeholder="请输入个人简介"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button type="primary" @click="updateForUser">
            保存修改
          </el-button>
          <el-button @click="resetForm">
            重置
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>

import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { userInfoStore } from "@/store/userInfoStore.js";
import { userTokenStore } from "@/store/userTokenStore.js";
import { UserAvatarService, UserUpdateService } from "@/api/user.js";

const InfoStore = userInfoStore();
const TokenStore = userTokenStore();

const uploadRef = ref(null);
const imgUrl = ref(InfoStore.info.user_pic || '');
const userInfo = ref({...InfoStore.info});

const rules = {
  nickname: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { pattern: /^\S{2,10}$/, message: '用户名必须是2-10位的非空字符串', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ]
};

const FileUpload = (result) => {
  imgUrl.value = result.data;
  console.log(imgUrl.value)
  ElMessage.success("头像上传成功！");
};

const handleUploadError = (error) => {
  ElMessage.error("头像上传失败，请重试");
  console.error('上传错误:', error);
};

const updateForUser = async () => {
  try {
    const params = {
      id: userInfo.value.id,
      username: userInfo.value.username,
      nickname: userInfo.value.nickname,
      email: userInfo.value.email,
      user_profile: userInfo.value.user_profile,
    };
    
    const result = await UserUpdateService(params);
    
    if (imgUrl.value !== InfoStore.info.user_pic) {
      await UserAvatarService(imgUrl.value);
      console.log(InfoStore.info.user_pic);
      InfoStore.info.user_pic = imgUrl.value;
      console.log(InfoStore.info.user_pic);
    }
    
    ElMessage.success(result.data || "资料更新成功");
    InfoStore.fetchLoginUser();
  } catch (error) {
    ElMessage.error("更新失败: " + error.message);
  }
};

const resetForm = () => {
  userInfo.value = {...InfoStore.info};
  imgUrl.value = InfoStore.info.user_pic || '';
  ElMessage.info("已重置为原始数据");
};

onMounted(() => {
  userInfo.value = {...InfoStore.info};
  imgUrl.value = InfoStore.info.user_pic || '';
});
</script>

<style lang="scss" scoped>
.user-profile-container {
  width: 900px;
  margin: 40px auto;
  padding: 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.page-title {
  text-align: center;
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 24px;
}

.profile-inner {
  display: flex;
  align-items: flex-start;
  gap: 40px;
}

/* 头像区域 */
.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 160px;
}

.avatar-wrapper {
  position: relative;
  margin-bottom: 24px;
}

.avatar-uploader {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px dashed #e4e7ed;
  background-color: #f5f7fa;
  cursor: pointer;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  color: #c0c4cc;
  font-size: 48px;
}

.change-avatar-btn {
  position: absolute;
  bottom: -20px;
  left: 50%;
  transform: translateX(-50%);
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 12px;
  opacity: 0.9;
  transition: opacity 0.3s;
  
  &:hover {
    opacity: 1;
  }
}

.username {
  font-size: 18px;
  font-weight: bold;

  /* 增加背景色 */
  background-color: #e0e0e0; 
  /* 圆角让背景更柔和 */
  border-radius: 4px; 
  /* 内边距，让文字和背景有距离 */
  padding: 6px 12px; 
  /* 让元素宽度适配内容，居中时更美观 */
  display: inline-block;   
} 


/* 表单区域 */
.form-section {
  flex: 1;
}

.el-form-item {
  margin-bottom: 16px;
}

.el-input--disabled .el-input__inner {
  background-color: #f5f7fa;
  color: #909399;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}
</style>